package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceivePurchase(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购需求单变成采购单
     *
     * @param mergeVo
     */
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            // 创建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // TODO 确认采购单转态是0，1才可以合并
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = mergeVo.getItems().stream()
                .filter(item -> {
                    PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item);
                    if (purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                            purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    }
                    return false;
                })
                .map(i -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setId(i);
                    purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                    purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                    return purchaseDetailEntity;
                }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Transactional
    @Override
    public void received(List<Long> ids) {
        // 1. 确认当前采购单是新建或者已分配
        List<PurchaseEntity> collect = ids.stream()
                .map(id -> {
                    PurchaseEntity purchaseEntity = this.getById(id);
                    return purchaseEntity;
                })
                .filter(item -> {
                    if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                            item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    }
                    return false;
                })
                .map(item -> {
                    item.setUpdateTime(new Date());
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    return item;
                })
                .collect(Collectors.toList());

        // 更新采购单
        this.updateBatchById(collect);

        collect.forEach((item) -> {
            // 改变采购项的转态
            List<PurchaseDetailEntity> list = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect1 = list.stream()
                    .map(entity -> {
                        PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                        purchaseDetailEntity.setId(item.getId());
                        purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                        return purchaseDetailEntity;
                    }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect1);
        });


    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo vo) {
        // 查询这个采购单
        Long id = vo.getId();
        AtomicReference<Boolean> flg = new AtomicReference<>(true); // 标志位，标志订单是否完成
        List<PurchaseDetailEntity> updates = new ArrayList<>(); // 需要更新的

        // 修改采购项的状态
        vo.getItems().forEach(
                i -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setId(i.getItemId());
                    purchaseDetailEntity.setStatus(i.getStatus());
                    updates.add(purchaseDetailEntity);
                    if (i.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                        flg.set(false);
                    } else {
                        // 将采购单入库(从数据库获取真实的数据)
                        PurchaseDetailEntity entity = purchaseDetailService.getById(i.getItemId());
                        wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
                    }
                });

        purchaseDetailService.updateBatchById(updates);

        // 修改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);

        if (flg.get()) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());

        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        this.baseMapper.updateById(purchaseEntity);
    }

}